package cn.tsyz.local.util;

import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CookieUtil {

    private static final String TOKEN_COOKIE_NAME = "AUTH_TOKEN";

    /**
     * 设置认证Token Cookie
     */
    public void setTokenCookie(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie(TOKEN_COOKIE_NAME, token);
        cookie.setHttpOnly(true); // 防止XSS攻击
        cookie.setSecure(false); // 在HTTPS环境下应设为true
        cookie.setPath("/"); // 对所有路径有效
        cookie.setMaxAge(7 * 24 * 60 * 60); // 7天过期
        response.addCookie(cookie);
    }

    /**
     * 从请求中获取Token Cookie
     */
    public String getTokenFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (TOKEN_COOKIE_NAME.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 删除Token Cookie
     */
    public void removeTokenCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie(TOKEN_COOKIE_NAME, null);
        cookie.setHttpOnly(true);
        cookie.setSecure(false);
        cookie.setPath("/");
        cookie.setMaxAge(0); // 立即过期
        response.addCookie(cookie);
    }
}
